// pages/chapter/chapter.js
const app = getApp();
const computedBehavior = require("miniprogram-computed").behavior;
Page({

  /**
   * 页面的初始数据
   */
  behaviors: [computedBehavior],
  data: {
    chapterList: [],
    bookInfo: {},
    active: 0,
    start: 0,
    limit: 50
  },
  computed: {
    showList(data) {
      return data.chapterList.slice(0, data.start + data.limit);
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (!app.globalData?.chapterList?.length) {
      wx.navigateTo({
        url: '/pages/index/index',
      });
      return;
    };
    this.setData({
      chapterList: app.globalData.chapterList,
      bookInfo: app.globalData.bookInfo,
    });
  },
  //滚动触底
  scrollBottom() {
    this.setData({
      start: this.data.start + this.data.limit
    })
  },
  //跳转阅读页
  toRead(e) {
    let {
      item,
      index
    } = e.currentTarget.dataset;
    console.log(item,"item");
    if (!item) return;
    if (!item.needPay) {
      wx.navigateTo({
        url: `/pages/read/read?id=${this.data.bookInfo.id}&uuid=${item.uuid}&title=${this.data.bookInfo.title}`,
      });
      let read = wx.getStorageSync('read') || [];
      read = [{
        ...this.data.bookInfo,
        readPage: index
      }, ...read.filter(el => {
        el.id != this.data.bookInfo.id
      })];
      console.log(read,"read");
      wx.setStorageSync('read', read);
      this.setData({
        active:index
      })
    } else {
      wx.showToast({
        title: '付费章节',
        icon: "error"
      });
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let read = wx.getStorageSync('read') || [];
    let list = read.filter(el => el.id == app.globalData.bookInfo.id);
    let readPage = 0;
    if(list.length){
      console.log(list);
      readPage = list[0].readPage;
    }
    console.log(readPage,'prasdsx');
    this.setData({
      active:readPage
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})